package com.software.human.activity;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;

import android.annotation.SuppressLint;
import android.app.DatePickerDialog;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.Toast;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.software.human.R;
import com.software.human.entity.UserInfo;
import com.software.human.util.OkHttpUtil;
import com.software.human.util.Result;

import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

public class UserInfoAddActivity extends AppCompatActivity implements DatePickerDialog.OnDateSetListener{

    private EditText  edt_user_name;
    private EditText edt_user_birth;
    private EditText edt_user_weight;
    private EditText edt_user_height;
    private EditText edt_user_sex;
    private Button btn_user_save;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_user_info_add);
        initViews();
        initEvents();
    }

    private void initEvents() {
        edt_user_birth.setOnClickListener(v -> {
            Calendar calendar = Calendar.getInstance();
            DatePickerDialog dialog = new DatePickerDialog(
                    this,
                    this,
                    calendar.get(Calendar.YEAR),
                    calendar.get(Calendar.MONTH),
                    calendar.get(Calendar.DAY_OF_MONTH)

            );
            dialog.show();
        });

        btn_user_save.setOnClickListener(v -> {
            // 把用户填写的内容封装成UserInfo对象，然后调用后台的保存接口进行保存
            UserInfo userInfo = new UserInfo();
            userInfo.setUserName(edt_user_name.getText().toString());
            userInfo.setSex(edt_user_sex.getText().toString());
            try {
                userInfo.setBirthday(new SimpleDateFormat("yyyy-MM-dd").parse(edt_user_birth.getText().toString()));
            } catch (ParseException e) {
                throw new RuntimeException(e);
            }
            userInfo.setHeight(Integer.valueOf(edt_user_height.getText().toString()));
            userInfo.setWeight(Float.valueOf(edt_user_weight.getText().toString()));
            saveUserInfo(userInfo);
        });
    }

    private void saveUserInfo(UserInfo userInfo) {
        String url = getString(R.string.system_url);
        OkHttpClient okHttp = OkHttpUtil.getInstance("");
        Gson gson = new GsonBuilder()
                .setDateFormat("yyyy-MM-dd")
                .create();
        String json = gson.toJson(userInfo);
        RequestBody requestBody  = RequestBody.create(json, MediaType.parse("application/json;charset=utf8"));
        Request request = new Request.Builder()
                .url(url + "/userInfo/add")
                .post(requestBody)
                .build();
        Call call = okHttp.newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(@NonNull Call call, @NonNull IOException e) {

            }

            @Override
            public void onResponse(@NonNull Call call, @NonNull Response response) throws IOException {
                if (response.isSuccessful()) {
                    String body = response.body().string();
                    Result<UserInfo> result = gson.fromJson(body, new Result<UserInfo>(){}.getClass());
                    // 更新UI
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            if (result.getCode() != 200) {
                                Toast.makeText(UserInfoAddActivity.this, result.getMsg(), Toast.LENGTH_SHORT).show();
                            } else {

                                Intent intent = new Intent(
                                        UserInfoAddActivity.this,
                                        UserInfoListActivity.class
                                );
                                startActivity(intent);
                                Toast.makeText(UserInfoAddActivity.this, "保存成功", Toast.LENGTH_SHORT).show();
                            }
                        }
                    });
                }

            }
        });

    }

    private void initViews() {
        edt_user_name = findViewById(R.id.edt_user_name);
        edt_user_birth = findViewById(R.id.edt_user_birth);
        edt_user_sex = findViewById(R.id.edt_user_sex);
        edt_user_height = findViewById(R.id.edt_user_height);
        edt_user_weight = findViewById(R.id.edt_user_weight);
        btn_user_save = findViewById(R.id.btn_user_save);
    }

    @Override
    public void onDateSet(DatePicker view, int year, int month, int dayOfMonth) {
        // 把用户选择的日期设置到生日输入框中
        month = month + 1;
        String monthStr = month > 9 ? month + "" : "0" + month;
        String desc = String.format("%d-%s-%d", year, monthStr, dayOfMonth);
        edt_user_birth.setText(desc);
    }
}